package com.sqfw.project.knowledge.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.sqfw.common.constant.HttpStatus;
import com.sqfw.common.enums.knowledge.KlContentStatusEnum;
import com.sqfw.common.enums.knowledge.KlContentStatusTypeEnum;
import com.sqfw.common.enums.knowledge.KlHasStatusEnum;
import com.sqfw.common.enums.knowledge.KlHasTypeEnum;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.common.utils.PageUtils;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.framework.security.LoginUser;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.project.knowledge.domain.KlContentFileInfo;
import com.sqfw.project.knowledge.domain.KlContentInfo;
import com.sqfw.project.knowledge.domain.KlContentStatusLog;
import com.sqfw.project.knowledge.domain.KlHasNotwrong;
import com.sqfw.project.knowledge.domain.KnowledgeSort;
import com.sqfw.project.knowledge.domain.query.KlHasNotwrongQuery;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoCountVo;
import com.sqfw.project.knowledge.domain.vo.KlHasNotwrongCountVo;
import com.sqfw.project.knowledge.mapper.KlContentFileInfoMapper;
import com.sqfw.project.knowledge.mapper.KlContentInfoMapper;
import com.sqfw.project.knowledge.mapper.KlContentStatusLogMapper;
import com.sqfw.project.knowledge.mapper.KlHasNotwrongMapper;
import com.sqfw.project.knowledge.mapper.KnowledgeSortMapper;
import com.sqfw.project.knowledge.service.KlContentService;
import com.sqfw.project.knowledge.service.KlHasNotwrongService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.system.service.ISysDictDataService;
import com.sqfw.project.wp.domain.TSmsSendLog;
import com.sqfw.project.wp.domain.TSmsUser;
import com.sqfw.project.wp.service.TSMSSendLogService;
import com.sqfw.project.wp.service.TSmsUserService;
import com.sqfw.project.wpReport.domain.WpHoliday;
import com.sqfw.project.wpReport.mapper.WpHolidayMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 【查无纠错数据表】Service业务层处理
 * 
 * @author tangxt
 * @date 2023-06-09
 */
@Slf4j
@Service
public class KlHasNotwrongServiceImpl implements KlHasNotwrongService
{
    @Autowired
    private KlHasNotwrongMapper klHasNotwrongMapper;

    @Autowired
    private KlContentService klContentService;

    @Autowired
    private KnowledgeSortMapper knowledgeSortMapper;

    @Autowired
    private KlContentStatusLogMapper klContentStatusLogMapper;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private KlContentFileInfoMapper klContentFileInfoMapper;

    @Autowired
    private TSMSSendLogService tsmsSendLogService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    public KlContentInfoMapper klContentInfoMapper;

    @Autowired
    private TSmsUserService tSmsUserService;

    @Autowired
    private WpHolidayMapper wpHolidayMapper;

    private final static long TIME_3_DAY = 3 * 24 * 60 * 60 * 1000;
    private final static long TIME_2_DAY = 2 * 24 * 60 * 60 * 1000;
    private final static long TIME_1_DAY = 24 * 60 * 60 * 1000;

    /**
     * 查询查无/纠错数据
     *
     * @param id 查无/纠错数据主键
     * @return 查无/纠错数据
     */
    @Override
    public KlHasNotwrong selectKlHasNotwrongById(String id) {
        KlHasNotwrong klHasNotwrong = klHasNotwrongMapper.selectKlHasNotwrongById(id);
        // 0 提交待审核, 3 待处理, 5 办结待审核, -1 已归档, -2 提交审核退回, -3 办结审核退回
        KlHasStatusEnum klHasStatusEnum = KlHasStatusEnum.by(klHasNotwrong.getKlHasStatus());
        klHasNotwrong.setKlHasStatusDesc(klHasStatusEnum != null ? klHasStatusEnum.getDesc() : "");
        // 查无知识分类描述
        if (StringUtils.isNotBlank(klHasNotwrong.getKlHasSort())) {
            KnowledgeSort knowledgeSort = knowledgeSortMapper.selectKnowledgeSortByAutoid(klHasNotwrong.getKlHasSort());
            if (knowledgeSort != null) {
                klHasNotwrong.setKlHasSortDesc(knowledgeSort.getSortname());
            }
        }
        // 审核记录
        KlContentStatusLog klContentStatusLog = new KlContentStatusLog();
        klContentStatusLog.setKlId(klHasNotwrong.getId());
        klContentStatusLog.setStatusType(KlContentStatusTypeEnum.CHECK_NONE_ERROR_CORRECTION.getKey());
        List<KlContentStatusLog> statusLogs = klContentStatusLogMapper.queryKlContentStatusLogListAsc(klContentStatusLog);
        if (!CollectionUtils.isEmpty(statusLogs)) {
            klHasNotwrong.setStatusLogList(statusLogs);
        }
        // 查询关联的文件
        KlContentFileInfo klContentFileInfo = new KlContentFileInfo();
        klContentFileInfo.setKlContentId(id);
        klContentFileInfo.setKlFileIsDel("0");
        List<KlContentFileInfo> fileInfoList = klContentFileInfoMapper.selectKlContentFileInfoList(klContentFileInfo);
        if (!CollectionUtils.isEmpty(fileInfoList)) {
            klHasNotwrong.setFileList(fileInfoList);
        }
        // 知识形式
        klHasNotwrong.setKlHasKnowledgeTypeDesc(dictDataService.selectDictLabel("knowledge_shape", klHasNotwrong.getKlHasKnowledgeType()));
        // 查询处理单位名称
        if (StringUtils.isNotBlank(klHasNotwrong.getProcessingDeptId())) {
            SysDept sysDept = deptMapper.selectDeptById(Long.parseLong(klHasNotwrong.getProcessingDeptId()));
            if (sysDept != null) {
                klHasNotwrong.setProcessingDeptName(sysDept.getDeptName());
            }
        }
        return klHasNotwrong;
    }

    /**
     * 查询查无/纠错数据列表
     *
     * @param klHasNotwrong 查无/纠错数据
     * @return 查无/纠错数据
     */
    @Override
    public List<KlHasNotwrong> selectKlHasNotwrongList(KlHasNotwrong klHasNotwrong)
    {
        return klHasNotwrongMapper.selectKlHasNotwrongList(klHasNotwrong);
    }

    /**
     * 新增【查无纠错数据表】
     * 
     * @param klHasNotwrong 【查无纠错数据表】
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertKlHasNotwrong(KlHasNotwrong klHasNotwrong) {
        // 0 提交待审核
        klHasNotwrong.setKlHasStatus(KlHasStatusEnum.SUBMIT_FOR_REVIEW.getKey());
        // 创建时间
        klHasNotwrong.setKlHasCreatime(new Date());
        klHasNotwrong.setKlHasUpdatetime(new Date());
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 创建人
        klHasNotwrong.setKlHasCreateperson(loginUser.getUserId().toString());
        // 部门
        klHasNotwrong.setKlHasDeptId(loginUser.getDeptId().toString());
        // 创建人工号
        klHasNotwrong.setKlHasAgentCode(loginUser.getUser().getCode());
        // 是否删除：0:否；1是
        klHasNotwrong.setKlHasIsdel("0");
        //创建用户的真实姓名
        klHasNotwrong.setKlHasRealName(loginUser.getUser().getNickName());
        int i =  klHasNotwrongMapper.insertKlHasNotwrong(klHasNotwrong);
        if (i > 0) {
            if (!CollectionUtils.isEmpty(klHasNotwrong.getFileIdList())) {
                klContentService.createAssociation(klHasNotwrong.getFileIdList(), klHasNotwrong.getId());
            }
            klContentService.addKlOperationsLog("添加查无纠错", JSON.toJSONString(klHasNotwrong), "成功", null);
            return i;
        }
        klContentService.addKlOperationsLog("添加查无纠错", JSON.toJSONString(klHasNotwrong), "失败", "查无纠错数据-insert-失败");
        return 0;
    }

    /**
     * 修改【查无纠错数据表】
     * 
     * @param klHasNotwrong 【查无纠错数据表】
     * @return 结果
     */
    @Override
    public int updateKlHasNotwrong(KlHasNotwrong klHasNotwrong) {
        int i = klHasNotwrongMapper.updateKlHasNotwrong(klHasNotwrong);
        return i;
    }

    @Override
    public int updateKlHasNotwrongFile(KlHasNotwrong klHasNotwrong) {
        int i = klHasNotwrongMapper.updateKlHasNotwrong(klHasNotwrong);
        // 修改知识关联文件id
        klContentService.updateAssociation(klHasNotwrong.getFileIdList(), klHasNotwrong.getId());
        return i;
    }


    /**
     * 批量删除查无/纠错数据
     *
     * @param ids 需要删除的查无/纠错数据主键
     * @return 结果
     */
    @Override
    public int deleteKlHasNotwrongByIds(String[] ids)
    {
        return klHasNotwrongMapper.deleteKlHasNotwrongByIds(ids);
    }

    /**
     * 删除查无/纠错数据信息
     *
     * @param id 查无/纠错数据主键
     * @return 结果
     */
    @Override
    public int deleteKlHasNotwrongById(String id) {
        return klHasNotwrongMapper.deleteKlHasNotwrongById(id);
    }

    /**
     * 审核---传递当前状态
     * 第一层审核：提交待审核--->待处理
     * 第二层审核：待处理--->办结待审核,提交审核退回
     * 第三层审核：办结待审核--->已归档,办结审核退回
     * @param klHasNotwrong
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult toExamineKlHasNotwrong(HttpServletRequest request, KlHasNotwrong klHasNotwrong) {
        KlHasNotwrong oldKlHasNotwrong = klHasNotwrongMapper.selectKlHasNotwrongById(klHasNotwrong.getId());
        // 检查传递的当前状态和数据库的状态是否相同，不相同就返回错误
        if (!oldKlHasNotwrong.getKlHasStatus().equals(klHasNotwrong.getKlHasStatus())) {
            return AjaxResult.error("审核失败，当前状态：" + KlHasStatusEnum.by(oldKlHasNotwrong.getKlHasStatus()).getDesc());
        }
        klHasNotwrong.setKlHasType(oldKlHasNotwrong.getKlHasType());
        // 第一层审核当前状态---0 提交待审核/-2 提交审核退回
        if (KlHasStatusEnum.SUBMIT_FOR_REVIEW.getKey().equals(klHasNotwrong.getKlHasStatus())
                || KlHasStatusEnum.SUBMIT_FOR_REVIEW_AND_RETURN.getKey().equals(klHasNotwrong.getKlHasStatus())) {
            // 需要传递下一级处理的部门id(前提提条件，是审核通过)
            if (KlContentStatusEnum.APPROVED.getKey().equals(klHasNotwrong.getAuditStatus()) &&
                    StringUtils.isBlank(klHasNotwrong.getProcessingDeptId())) {
                return AjaxResult.error("处理部门必传！");
            }
            // 通过---->3 待处理
            if (KlContentStatusEnum.APPROVED.getKey().equals(klHasNotwrong.getAuditStatus())) {
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.PENDING_PROCESSING.getKey());
            }else { // 不通过--->-1 已归档
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.ARCHIVED.getKey());
                klHasNotwrongMapper.updateKlHasNotwrongById(klHasNotwrong.getId());
            }
            klHasNotwrong.setSubmitProcessTime(new Date());
        // 第二层审核---3 待处理/-3 办结审核退回
        }else if (KlHasStatusEnum.PENDING_PROCESSING.getKey().equals(klHasNotwrong.getKlHasStatus())
                || KlHasStatusEnum.COMPLETED_REVIEW_RETURN.getKey().equals(klHasNotwrong.getKlHasStatus())) {
            klHasNotwrong.setIsRead(false);
            // 通过---->5 办结待审核
            if (KlContentStatusEnum.APPROVED.getKey().equals(klHasNotwrong.getAuditStatus())) {
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.COMPLETED_FOR_REVIEW.getKey());
            }else { // 不通过--->-2 提交审核退回
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.SUBMIT_FOR_REVIEW_AND_RETURN.getKey());
            }
            // 如果是查无，获取知识数据中的标题，关键字(0：查无；1纠错)
            if (KlHasTypeEnum.CHECK_NONE.getKey().equals(klHasNotwrong.getKlHasType())
                    && StringUtils.isNotBlank(klHasNotwrong.getKlId())) {
                // 根据id查询知识库
                KlContentInfo klContentInfo = klContentService.selectKlContentInfoByKlId(klHasNotwrong.getKlId());
                klHasNotwrong.setKlHasTitle(klContentInfo.getKlContentTitle());
                klHasNotwrong.setKlHasKeyword(klContentInfo.getKlContentKeyword());
            }
            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            klHasNotwrong.setKlHasProcessingUserid(loginUser.getUserId().toString());
            klHasNotwrong.setKlHasProcessingUsername(loginUser.getUser().getNickName());
            klHasNotwrong.setKlHasProcessingTime(new Date());
        // 第三层审核---5 办结待审核
        }else if (KlHasStatusEnum.COMPLETED_FOR_REVIEW.getKey().equals(klHasNotwrong.getKlHasStatus())) {
            klHasNotwrong.setIsRead(false);
            // 通过---->-1 已归档
            if (KlContentStatusEnum.APPROVED.getKey().equals(klHasNotwrong.getAuditStatus())) {
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.ARCHIVED.getKey());
                klHasNotwrong.setThreeUpdateUserId(SecurityUtils.getLoginUser().getUserId());
            }else { // 不通过--->-3 办结审核退回
                klHasNotwrong.setKlHasStatus(KlHasStatusEnum.COMPLETED_REVIEW_RETURN.getKey());
            }
        }else {
            return AjaxResult.error("该状态不允许审核");
        }
        klHasNotwrong.setKlHasUpdatetime(new Date());
        int i = klHasNotwrongMapper.updateKlHasNotwrong(klHasNotwrong);
        if (i > 0) {
            // 修改知识关联文件id
            klContentService.updateAssociation(klHasNotwrong.getFileIdList(), klHasNotwrong.getId());
            // 添加审核意见数据(审核-通过或者不通过)
            klContentService.addKlContentStatusLog(klHasNotwrong.getId(), klHasNotwrong.getAuditStatus(),
                    klHasNotwrong.getReviewComment(), klHasNotwrong.getKlHasStatus(), KlContentStatusTypeEnum.CHECK_NONE_ERROR_CORRECTION.getKey());
            // 发送短信给承办单位(条件：修改的-待处理和审核通过)
            if (KlHasStatusEnum.PENDING_PROCESSING.getKey().equals(klHasNotwrong.getKlHasStatus()) &&
                    KlContentStatusEnum.APPROVED.getKey().equals(klHasNotwrong.getAuditStatus())) {
                // 发送短信
                this.sendSmsBatch(request, klHasNotwrong);
            }
            // 跟踪日志
            klContentService.addKlOperationsLog("审核查无纠错", JSON.toJSONString(klHasNotwrong), "成功", null);
            return AjaxResult.success("审核成功");
        }
        klContentService.addKlOperationsLog("审核查无纠错", JSON.toJSONString(klHasNotwrong), "失败", "审核纠错数据-update-失败");
        return AjaxResult.error("审核失败");
    }

    /**
     * 分页查询-根据部门查询/根据部门+in 状态查询
     * @param query
     * @return
     * */
    @Override
    public List<KlHasNotwrong> queryKlHasNotwrongByDept(KlHasNotwrongQuery query) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!"admin".equals(loginUser.getUser().getCode())) {
            // 部门id
            query.setProcessingDeptId(loginUser.getDeptId().toString());
        }
        List<KlHasNotwrong> klHasNotwrongList = klHasNotwrongMapper.queryKlHasNotwrongList(query);
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        // 查询所有的知识形式
        SysDictData dictData = new SysDictData();
        dictData.setDictType("knowledge_shape");
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
        for (KlHasNotwrong h : klHasNotwrongList) {
            // 状态
            KlHasStatusEnum klHasStatusEnum = KlHasStatusEnum.by(h.getKlHasStatus());
            h.setKlHasStatusDesc(klHasStatusEnum != null ? klHasStatusEnum.getDesc() : "");
            // 知识类型(知识分类)
            for (KnowledgeSort sort : knowledgeSortList) {
                if (sort.getAutoid().equals(h.getKlHasSort())) {
                    h.setKlHasSortDesc(sort.getSortname());
                    break;
                }
            }
            // 知识形式
            for (SysDictData sysDictData : sysDictDataList) {
                if (sysDictData.getDictValue().equals(h.getKlHasKnowledgeType())) {
                    h.setKlHasKnowledgeTypeDesc(sysDictData.getDictLabel());
                    break;
                }
            }
            // 0：查无；1纠错
            if (KlHasTypeEnum.CHECK_NONE.getKey().equals(h.getKlHasType())) {
                // 更新时间大于两天，黄色预警提醒
                if (System.currentTimeMillis() - h.getKlHasUpdatetime().getTime() > 2 * 24 * 60 * 60 * 1000) {
                    h.setIsYellowAlert(true);
                }
            }else if (KlHasTypeEnum.ERROR_CORRECTION.getKey().equals(h.getKlHasType())) {
                h.setIsYellowAlert(true);
            }
            // klHasStatus: 已归档的不计算
            if (!KlHasStatusEnum.ARCHIVED.getKey().equals(h.getKlHasStatus())) {
                // 展示，“警”字或者“超”字
                if (h.getKlHasUpdatetime() != null) {
                    // 判断是否＞两天
                    long timeDay = System.currentTimeMillis() - h.getKlHasUpdatetime().getTime();
                    if (timeDay > TIME_2_DAY) {
                        Map<String, String> map = new HashMap<>();
                        map.put("startDtime", DateUtils.dateTime(h.getKlHasUpdatetime()));
                        map.put("endDtime", DateUtils.dateTime(new Date()));
                        // 查询节假日t
                        List<WpHoliday> wpHolidayList = wpHolidayMapper.selectWpHolidayByDtime(map);
                        if (!CollectionUtils.isEmpty(wpHolidayList)) {
                            boolean isHolid = false;
                            // 今天特殊处理，今天是否是节假日
                            for (WpHoliday wpHoliday : wpHolidayList) {
                                // 相同，是节假日
                                if (DateUtils.dateTime(new Date()).equals(DateUtils.dateTime(wpHoliday.getDtime()))) {
                                    isHolid = true;
                                    break;
                                }
                            }
                            // 今天是节假日
                            if (isHolid) {
                                long holiday = (wpHolidayList.size() -1) * 24 * 60 * 60 * 1000;
                                long time = System.currentTimeMillis() - DateUtils.parseDate(DateUtils.dateTime(new Date())).getTime();
                                holiday = holiday + time;
                                timeDay = timeDay - holiday;
                            }else {
                                long holiday = wpHolidayList.size() * 24 * 60 * 60 * 1000;
                                timeDay = timeDay - holiday;
                            }
                            if (timeDay > TIME_2_DAY) {
                                h.setDisplayWord("警");
                            }
                            if (timeDay > 3 * 24 * 60 * 60 * 1000) {
                                h.setDisplayWord("超");
                            }
                        }else {
                            if (timeDay > TIME_2_DAY) {
                                h.setDisplayWord("警");
                            }
                            if (timeDay > 3 * 24 * 60 * 60 * 1000) {
                                h.setDisplayWord("超");
                            }
                        }
                    }
                }
            }
            // 类型
            KlHasTypeEnum klHasTypeEnum = KlHasTypeEnum.by(h.getKlHasType());
            h.setKlHasTypeDesc(klHasTypeEnum != null ? klHasTypeEnum.getDesc() : "");
        }
        return klHasNotwrongList;
    }

    /**
     * 分页查询--根据in查询 状态
     * @param query
     * @return
     * */
    @Override
    public List<KlHasNotwrong> queryKlHasNotwrongList(KlHasNotwrongQuery query) {
        // 分页查询查无
        List<KlHasNotwrong> klHasNotwrongList = klHasNotwrongMapper.queryKlHasNotwrongList(query);
        // 查询所有的知识分类
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        // 查询所有的知识形式
        SysDictData dictData = new SysDictData();
        dictData.setDictType("knowledge_shape");
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
        for (KlHasNotwrong h : klHasNotwrongList) {
            KlHasStatusEnum klHasStatusEnum = KlHasStatusEnum.by(h.getKlHasStatus());
            // 查无纠错状态
            h.setKlHasStatusDesc(klHasStatusEnum != null ? klHasStatusEnum.getDesc() : "");
            // 知识分类
            for (KnowledgeSort sort : knowledgeSortList) {
                if (sort.getAutoid().equals(h.getKlHasSort())) {
                    h.setKlHasSortDesc(sort.getSortname());
                    break;
                }
            }
            // 知识形式
            for (SysDictData sysDictData : sysDictDataList) {
                if (sysDictData.getDictValue().equals(h.getKlHasKnowledgeType())) {
                    h.setKlHasKnowledgeTypeDesc(sysDictData.getDictLabel());
                    break;
                }
            }
            // klHasStatus: 已归档的不计算
            if (!KlHasStatusEnum.ARCHIVED.getKey().equals(h.getKlHasStatus())) {
                // 展示，“警”字或者“超”字
                if (h.getKlHasUpdatetime() != null) {
                    // 判断是否＞两天
                    long timeDay = System.currentTimeMillis() - h.getKlHasUpdatetime().getTime();
                    if (timeDay > TIME_2_DAY) {
                        Map<String, String> map = new HashMap<>();
                        map.put("startDtime", DateUtils.dateTime(h.getKlHasUpdatetime()));
                        map.put("endDtime", DateUtils.dateTime(new Date()));
                        // 查询节假日t
                        List<WpHoliday> wpHolidayList = wpHolidayMapper.selectWpHolidayByDtime(map);
                        if (!CollectionUtils.isEmpty(wpHolidayList)) {
                            boolean isHolid = false;
                            // 今天特殊处理，今天是否是节假日
                            for (WpHoliday wpHoliday : wpHolidayList) {
                                // 相同，是节假日
                                if (DateUtils.dateTime(new Date()).equals(DateUtils.dateTime(wpHoliday.getDtime()))) {
                                    isHolid = true;
                                    break;
                                }
                            }
                            // 今天是节假日
                            if (isHolid) {
                                long holiday = (wpHolidayList.size() -1) * 24 * 60 * 60 * 1000;
                                long time = System.currentTimeMillis() - DateUtils.parseDate(DateUtils.dateTime(new Date())).getTime();
                                holiday = holiday + time;
                                timeDay = timeDay - holiday;
                            }else {
                                long holiday = wpHolidayList.size() * 24 * 60 * 60 * 1000;
                                timeDay = timeDay - holiday;
                            }
                            if (timeDay > TIME_2_DAY) {
                                h.setDisplayWord("警");
                            }
                            if (timeDay > 3 * 24 * 60 * 60 * 1000) {
                                h.setDisplayWord("超");
                            }
                        }else {
                            if (timeDay > TIME_2_DAY) {
                                h.setDisplayWord("警");
                            }
                            if (timeDay > 3 * 24 * 60 * 60 * 1000) {
                                h.setDisplayWord("超");
                            }
                        }
                    }
                }
            }
            // 类型
            KlHasTypeEnum klHasTypeEnum = KlHasTypeEnum.by(h.getKlHasType());
            h.setKlHasTypeDesc(klHasTypeEnum != null ? klHasTypeEnum.getDesc() : "");
        }
        return klHasNotwrongList;
    }

    /**
     * 承办单位点击处理，标记该工单已经阅读
     * @param klHasNotwrong id
     * @return
     * */
    @Override
    public AjaxResult updateRead(KlHasNotwrong klHasNotwrong) {
        KlHasNotwrong oldKlHasNotwrong = klHasNotwrongMapper.selectKlHasNotwrongById(klHasNotwrong.getId());
        if (oldKlHasNotwrong == null) {
            return AjaxResult.error("该id不存在");
        }
        // 判断审核状态是否是：待处理
        if (KlHasStatusEnum.PENDING_PROCESSING.getKey().equals(oldKlHasNotwrong.getKlHasStatus()) ||
                KlHasStatusEnum.COMPLETED_REVIEW_RETURN.getKey().equals(oldKlHasNotwrong.getKlHasStatus())) {
            KlHasNotwrong newKlHasNotwrong = new KlHasNotwrong();
            newKlHasNotwrong.setId(klHasNotwrong.getId());
            newKlHasNotwrong.setIsRead(klHasNotwrong.getIsRead());
            klHasNotwrongMapper.updateKlHasNotwrong(newKlHasNotwrong);
            return AjaxResult.success();
        }else {
            return AjaxResult.success("该状态无法审核");
        }
    }

    /**
     * 撤回（社区服务中心，派发给承办单位，发现错误了，撤回该查无/纠错）
     * @param klHasNotwrong 查无/纠错id
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult revokeKlHasNotwrong(KlHasNotwrong klHasNotwrong) {
        KlHasNotwrong oldKlHasNotwrong = klHasNotwrongMapper.selectKlHasNotwrongById(klHasNotwrong.getId());
        if (oldKlHasNotwrong == null) {
            return AjaxResult.error("该id不存在");
        }
        // 判断审核状态是否是：待处理
        if (!KlHasStatusEnum.PENDING_PROCESSING.getKey().equals(oldKlHasNotwrong.getKlHasStatus())) {
            AjaxResult result = AjaxResult.success("该查无/纠错状态：" +  KlHasStatusEnum.by(oldKlHasNotwrong.getKlHasStatus()).getDesc() + ", 不能撤回");
            result.put(AjaxResult.CODE_TAG, HttpStatus.NO_CONTENT);
            return result;
        }
        // 判断是否已经阅读
        if (oldKlHasNotwrong.getIsRead() != null && oldKlHasNotwrong.getIsRead()) {
            if (System.currentTimeMillis() - oldKlHasNotwrong.getKlHasUpdatetime().getTime() < 15 * 60 * 1000) {
                AjaxResult result = AjaxResult.success("该查无/纠错承办单位审核中");
                result.put(AjaxResult.CODE_TAG, HttpStatus.WARN);
                return result;
            }
        }
        KlHasNotwrong newKlHasNotwrong = new KlHasNotwrong();
        newKlHasNotwrong.setId(klHasNotwrong.getId());
        newKlHasNotwrong.setProcessingDeptId(null);
        newKlHasNotwrong.setKlHasStatus(KlHasStatusEnum.SUBMIT_FOR_REVIEW.getKey());
        newKlHasNotwrong.setKlHasUpdatetime(new Date());
        klHasNotwrongMapper.updateHasNotwrongById(newKlHasNotwrong);
        if (StringUtils.isBlank(klHasNotwrong.getReviewComment())) {
            klHasNotwrong.setReviewComment("撤回");
        }
        // 撤回审核记录
        klContentService.addKlContentStatusLog(klHasNotwrong.getId(), KlContentStatusEnum.REVOKE_NOTWRONG.getKey(),
                klHasNotwrong.getReviewComment(), newKlHasNotwrong.getKlHasStatus(), KlContentStatusTypeEnum.CHECK_NONE_ERROR_CORRECTION.getKey());
        return AjaxResult.success();
    }

    /**
     * 统计查无/纠错
     * 默认条件：-1 已归档，三级承办单位（处理单位）不能为空
     * 选择条件：主办单位（部门-只能选择最后一级），发起时间范围，姓名（真实姓名）
     * @param query
     * @return
     * */
    @Override
    public List<KlHasNotwrongCountVo> countKlHasNotwrong(KlHasNotwrongQuery query) {
        List<KlHasNotwrongCountVo> countVos = new ArrayList<>();
        // 查询所有符合提交的数据
        List<KlHasNotwrong> list = klHasNotwrongMapper.queryAllCountData(query);
        if (CollectionUtils.isEmpty(list)) {
            return countVos;
        }
        // 根据部门和真实姓名去重
        Map<String, KlHasNotwrongCountVo> countMap = new HashMap<>();
        list.parallelStream().forEach(klHasNotwrong -> {
            String key = klHasNotwrong.getProcessingDeptId() + "_" + klHasNotwrong.getKlHasProcessingUsername();
            if (countMap.containsKey(key)) {
                KlHasNotwrongCountVo countVo = countMap.get(key);
                if (KlHasTypeEnum.CHECK_NONE.getKey().equals(klHasNotwrong.getKlHasType())) {
                    countVo.setCheckNoneCount(countVo.getCheckNoneCount() + 1);
                    if (klHasNotwrong.getKlHasProcessingTime() != null &&
                            klHasNotwrong.getKlHasProcessingTime().getTime() - klHasNotwrong.getSubmitProcessTime().getTime() > TIME_3_DAY) {
                        countVo.setCheckNoneTimeout(countVo.getCheckNoneTimeout() + 1);
                    }
                }else if (KlHasTypeEnum.ERROR_CORRECTION.getKey().equals(klHasNotwrong.getKlHasType())) {
                    countVo.setErrorCorrectionCount(countVo.getErrorCorrectionCount() + 1);
                    if (klHasNotwrong.getKlHasProcessingTime() != null &&
                            klHasNotwrong.getKlHasProcessingTime().getTime() - klHasNotwrong.getSubmitProcessTime().getTime() > TIME_1_DAY) {
                        countVo.setErrorCorrectionTimeout(countVo.getErrorCorrectionTimeout() + 1);
                    }
                }
                countMap.put(key, countVo);
            }else {
                KlHasNotwrongCountVo countVo = new KlHasNotwrongCountVo(klHasNotwrong.getProcessingDeptId(), klHasNotwrong.getProcessingDeptName(), klHasNotwrong.getKlHasProcessingUsername());
                if (KlHasTypeEnum.CHECK_NONE.getKey().equals(klHasNotwrong.getKlHasType())) {
                    countVo.setCheckNoneCount(1);
                    if (klHasNotwrong.getKlHasProcessingTime() != null &&
                            klHasNotwrong.getKlHasProcessingTime().getTime() - klHasNotwrong.getSubmitProcessTime().getTime() > TIME_3_DAY) {
                        countVo.setCheckNoneTimeout(1);
                    }
                }else if (KlHasTypeEnum.ERROR_CORRECTION.getKey().equals(klHasNotwrong.getKlHasType())) {
                    countVo.setErrorCorrectionCount(1);
                    if (klHasNotwrong.getKlHasProcessingTime() != null &&
                            klHasNotwrong.getKlHasProcessingTime().getTime() - klHasNotwrong.getSubmitProcessTime().getTime() > TIME_1_DAY) {
                        countVo.setErrorCorrectionTimeout(1);
                    }
                }
                countMap.put(key, countVo);
            }
        });
        List<KlContentInfoCountVo> klContentInfoCountVos = klContentInfoMapper.countByIsActiveAdd(query);
        countMap.entrySet().forEach(countVoMap -> {
            KlHasNotwrongCountVo countVo = countVoMap.getValue();
            Integer knowledgeCount = 0;
            for (KlContentInfoCountVo vo : klContentInfoCountVos) {
                if (countVo.getDeptId().equals(vo.getKlContentSources()) &&
                        countVo.getRealName().equals(vo.getKlContentCreaterName()) ) {
                    knowledgeCount = vo.getTypeCount();
                    break;
                }
            }
            countVo.setKnowledgeCount(knowledgeCount);
            countVo.setSubtotalCount(countVo.getCheckNoneCount() + countVo.getErrorCorrectionCount() + countVo.getKnowledgeCount());
            countVos.add(countVo);
        });
        List<KlHasNotwrongCountVo> klCountVoList = new ArrayList<>();
        klContentInfoCountVos.stream().forEach(vo -> {
            boolean isExist = false;
            for (KlHasNotwrongCountVo countVo : countVos) {
                if (vo.getKlContentSources().equals(countVo.getDeptId()) &&
                        vo.getKlContentCreaterName().equals(countVo.getRealName())) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                KlHasNotwrongCountVo countVo = new KlHasNotwrongCountVo(vo.getKlContentSources(), vo.getKlContentCreaterName(), vo.getTypeCount(), vo.getTypeCount());
                countVo.setDeptName(vo.getDeptName());
                klCountVoList.add(countVo);
            }
        });
        countVos.addAll(klCountVoList);
        return countVos;
    }


    /**
     * 发送短信
     * */
    private void sendSmsBatch(HttpServletRequest request, KlHasNotwrong klHasNotwrong) {
        // 单独线程发送短信
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 根据部门id，获取用户手机号发送短信
//                SysUser sysUser = new SysUser();
//                sysUser.setDeptId(Long.parseLong(klHasNotwrong.getProcessingDeptId()));
//                List<SysUser> userList = userMapper.selectUserList(sysUser);
                List<TSmsUser> smsUserList = tSmsUserService.getSmsUserList(Long.parseLong(klHasNotwrong.getProcessingDeptId()));
                StringBuffer receivePhones = new StringBuffer();
                if (CollectionUtils.isEmpty(smsUserList)) {
                    log.info("没有查询到用户手机号发送短信！");
                    return;
                }else if (smsUserList.size() == 1) {
                    if (StringUtils.isNotBlank(smsUserList.get(0).getMobile())) {
                        receivePhones.append(smsUserList.get(0).getMobile());
                    }
                }else {
                    for (int i = 0; i < smsUserList.size(); i++) {
                        if (StringUtils.isNotBlank(smsUserList.get(i).getMobile())) {
                            if (StringUtils.isBlank(receivePhones.toString())) {
                                receivePhones.append(smsUserList.get(i).getMobile());
                            }else {
                                receivePhones.append("," + smsUserList.get(i).getMobile());
                            }
                        }
                    }
                }
                if (StringUtils.isNotBlank(receivePhones.toString())) {
                    if (KlHasTypeEnum.CHECK_NONE.getKey().equals(klHasNotwrong.getKlHasType())) {  // 查无
                        tsmsSendLogService.sendSmsBatch(receivePhones.toString(), "查无工单短信");
                        log.info("发送查无工单短信");
                    }else {
                        tsmsSendLogService.sendSmsBatch(receivePhones.toString(), "纠错工单短信");
                        log.info("发送纠错工单短信");
                    }
                }
            }
        }).start();

    }



}
